#define WIN32_LEAN_AND_MEAN
#include <windows.h>

#include "GDynamicLibrary.h"
#include "../../Foundation/GUtilities/GError.h"

namespace GEngine
{
	void GDynamicLibrary::Unload() PLATFORM
	{
		if (Handle != NULL)
		{
			FreeModule((HMODULE)Handle);
			
			Handle = NULL;
			FileName.clear();
		}
	}

	bool GDynamicLibrary::Load(const char* Path) PLATFORM
	{
		GUtil::GError::DebugCheck(Handle != NULL, "Library is already loaded.");

		HMODULE hLibrary = LoadLibrary(Path);
		if (hLibrary == NULL)
		{
			GUtil::GError::Error(GUtil::GErrorMessageWin32(GetLastError()));
			return false;
		}

		FileName = Path;
		Handle = hLibrary;

		return true;
	}
		
	void* GDynamicLibrary::GetProcedure(const char* Name) PLATFORM
	{
		GUtil::GError::DebugCheck(Handle == NULL, "Library not loaded.");

		FARPROC Proc = GetProcAddress((HMODULE)Handle, Name);
		if (Proc == NULL)
		{
			GUtil::GError::Error(GUtil::GErrorMessageWin32(GetLastError()));
			return false;
		}
		return Proc;
	}
}